//
//  VideoViewController.m
//  OneDay
//
//  Created by oneDay on 15/10/16.
//  Copyright (c) 2015年 oneDay All rights reserved.
//

#import "VideoViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>

#import "VideoView.h"
#import "VideoTableViewCell.h"
#import "VideoCollectionViewCell.h"
#import "CategoriesTableViewController.h"
#import "LoginViewController.h"

@interface VideoViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, collectionSpecialVideoDelegate, UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *categoryArray;
@property (nonatomic, strong) NSString *string;

@property (nonatomic, strong) VideoView *videoView;
// 存放所有收藏的model
@property (nonatomic, strong) NSMutableArray *collectionArray;

@property (nonatomic, strong) UISegmentedControl *segment;

@property (nonatomic, assign) NSInteger lastContentOfSet;

@property (nonatomic, strong) MONActivityIndicatorView *indicatorView;

@end

@implementation VideoViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    // 视图每次出现的时候显示的都是scrollview的第一页
    self.segment.selectedSegmentIndex = 0;
    self.videoView.bgScrollView.contentOffset = CGPointMake(0, 0);
    [self.videoView.tableView.header endRefreshing];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addSubviews];
    
    [self refreshTableViewData];
    
}


- (void)addSubviews
{
    CGRect frame = [UIScreen mainScreen].bounds;
    self.videoView = [[VideoView alloc] initWithFrame:frame];
    self.view = self.videoView;
    
    NSArray *titleArray = @[@"每日精选", @"分类"];
    self.segment = [[UISegmentedControl alloc] initWithItems:titleArray];
    self.segment.frame = CGRectMake(50, 0, kWidth - 100, 30);
    self.segment.tintColor = [UIColor grayColor];
    self.segment.selectedSegmentIndex = 0;
    [self.segment addTarget:self action:@selector(changeTitle:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.segment;
    
    self.videoView.bgScrollView.delegate = self;
    
    self.videoView.tableView.delegate = self;
    self.videoView.tableView.dataSource = self;
    self.dataArray = [NSMutableArray array];
    [self requestVideoDataWithUrl:kFavoriteVideoUrl block:^(NSArray *array) {
        self.dataArray = [NSMutableArray arrayWithArray:array];
        [self.videoView.tableView reloadData];
    }];
    
    self.videoView.collectionView.delegate = self;
    self.videoView.collectionView.dataSource = self;
    [self.videoView.collectionView registerClass:[VideoCollectionViewCell class] forCellWithReuseIdentifier:@"VideoCollectionViewCell"];
    [self requestCategoriesDataWithUrl:kCategoryUrl block:^() {
        [self.videoView.collectionView reloadData];
    }];
}

- (void)changeTitle:(UISegmentedControl *)segment
{
    if (segment.selectedSegmentIndex == 0) {
        self.videoView.bgScrollView.contentOffset = CGPointMake(0, 0);
    } else if (segment.selectedSegmentIndex == 1) {
        self.videoView.bgScrollView.contentOffset = CGPointMake(kWidth, 0);
    }
    
}

#pragma mark - scrollView 的代理方法
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.lastContentOfSet = scrollView.contentOffset.x;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x < self.lastContentOfSet) {
        self.segment.selectedSegmentIndex = 0;
    } else if (scrollView.contentOffset.x > self.lastContentOfSet) {
        self.segment.selectedSegmentIndex = 1;
    }
}


#pragma mark - tableView 刷新
- (void)refreshTableViewData
{
    // 下拉刷新
    self.videoView.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh1)];
    self.videoView.tableView.footer = [MJRefreshBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh1)];
    // 进入刷新状态
    [self.videoView.tableView.header beginRefreshing];
}

- (void)footerRefresh1
{
    NSArray *strArray = [kFavoriteVideoUrl componentsSeparatedByString:@"?"];
    NSString *strUrl = [self.string stringByAppendingFormat:@"&%@", strArray.lastObject];
    [self requestVideoDataWithUrl:strUrl block:^(NSArray *array) {
        [self.dataArray addObjectsFromArray:array];
        [self.videoView.tableView reloadData];
    }];
    [self.videoView.tableView.footer endRefreshing];
    
}

- (void)headerRefresh1
{
    // 在这个方法中请求数据
    // 结束刷新状态
    [self.videoView.tableView.header endRefreshing];
}

#pragma mark - tableView 的代理方法
// 返回分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// 返回每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kHeight / 2.7 + 5;
}

// 返回脚
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 40;
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"videoTableCell";
    VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[VideoTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    // 取消选中的颜色
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    if (self.dataArray.count != 0) {
        
        cell.model = self.dataArray[indexPath.row];
    }
    [cell.shareButton addTarget:self action:@selector(shareButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.shareLabel addTarget:self action:@selector(shareButtonTwo :) forControlEvents:UIControlEventTouchUpInside];
    cell.shareButton.tag = indexPath.row + 1210;
    cell.shareLabel.tag = indexPath.row + 2000;
    cell.delegate = self;
    return cell;
}

- (void)shareButton:(UIButton *)sender
{
    NSLog(@"点击");
    VideoModel *model = self.dataArray[sender.tag - 1210];
    // 需要分享的文字
    NSString *str = [NSString stringWithFormat:@"OneDay推荐：%@，精彩微视频请看：%@", model.title, model.playUrl];
    // 图片
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.coverForDetail] placeholderImage:nil];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56396d0ee0f55aff4d0010a0"
                                      shareText:str
                                     shareImage:imageView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, UMShareToDouban,UMShareToEmail,UMShareToFacebook, nil]
                                       delegate:nil];
}

- (void)shareButtonTwo:(UIButton *)sender
{
    NSLog(@"点击");
    VideoModel *model = self.dataArray[sender.tag - 2000];
    // 需要分享的文字
    NSString *str = [NSString stringWithFormat:@"OneDay推荐：%@，精彩微视频请看：%@", model.title, model.playUrl];
    // 图片
    UIImageView *imageView = [[UIImageView alloc] init];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.coverForDetail] placeholderImage:nil];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"56396d0ee0f55aff4d0010a0"
                                      shareText:str
                                     shareImage:imageView.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, UMShareToDouban,UMShareToEmail,UMShareToFacebook, nil]
                                       delegate:nil];
}


// 收藏
- (void)collectionCellDidSelected:(VideoModel *)model
{
    UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    DataManager *manager = [DataManager shareManager];
    // 判断是否登录
    if ([manager isLogin] == NO) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        
        // 实现block
        loginVC.block = ^void(){
            NSLog(@"登录成功");
        };
        
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        [self presentViewController:navC animated:YES completion:nil];
    }else{
        LeanCloudObject *leanCloud = [[LeanCloudObject alloc] init];
        NSString *userName = [manager userName];
        // 先判断是否收藏过
        NSArray *videoArray = [leanCloud selectStundetWithStyle:@"video" userName:userName];
        BOOL isHave = NO;
        for (VideoObject *video in videoArray) {
            if ([video.title isEqualToString:model.title]) {
                isHave = YES;
                break;
            }
        }
        if (isHave == NO) {
            [leanCloud creatObjectWithTitle:model.title imageUrl:model.coverForDetail needString:model.playUrl style:@"video" userName:userName];
            [alertView show];
        }else{
            alertView.message = @"您已经收藏过了";
            [alertView show];
        }
        // 实现 2 秒回收
        [self performSelector:@selector(actionAlert:) withObject:alertView afterDelay:2];
    }
}
#pragma mark -- 实现2秒消失
- (void)actionAlert:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];// 三秒回收
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel *model = self.dataArray[indexPath.row];
    // 播放路径
    NSURL *url = [NSURL URLWithString:model.playUrl];
    AVPlayer *player = [AVPlayer playerWithURL:url];
    AVPlayerViewController *playerVC = [AVPlayerViewController new];
    playerVC.player = player;
    [self presentViewController:playerVC animated:YES completion:nil];
}

#pragma mark - collectionView 的代理方法 ----
// 返回分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

// 返回个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 12;
}

// 返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    VideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VideoCollectionViewCell" forIndexPath:indexPath];
    cell.model = self.categoryArray[indexPath.row];
    return cell;
}

// 点击跳转
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CategoriesTableViewController *categoriesVC = [[CategoriesTableViewController alloc] init];
    categoriesVC.row = indexPath.row;
    CategoryModel *model = self.categoryArray[indexPath.row];
    categoriesVC.navigationItem.title = model.name;
    [self.navigationController pushViewController:categoriesVC animated:YES];
}

#pragma mark - UICollectionViewDelegateFlowLayout ---
// 返回cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    return CGSizeMake(kWidth / 2 - 5, kHeight / 3.4);
}



#pragma mark - video 每日精选 数据请求 ----
- (void)requestVideoDataWithUrl:(NSString *)url block:(void (^)(NSArray *array))block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setHTTPMethod:@"GET"];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 保护方法
            if (data == nil) {
                return ;
            }
            NSDictionary *rootDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            // 下页的拼接网址
            self.string = rootDictionary[@"nextPageUrl"];
            NSArray *tempArray1 = rootDictionary[@"dailyList"];
            NSDictionary *tempDic = tempArray1.firstObject;
            NSArray *tempArray2 = tempDic[@"videoList"];
            
            // 数组初始化
            NSMutableArray *array = [NSMutableArray array];
            // 遍历数组
            for (NSDictionary *dic in tempArray2) {
                VideoModel *model = [[VideoModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [array addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block(array);
            });
        }];
        [dataTask resume];
    });
}

#pragma mark - video 分类请求数据
- (void)requestCategoriesDataWithUrl:(NSString *)url block:(void (^)(void))block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setHTTPMethod:@"GET"];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 保护方法
            if (data == nil) {
                return ;
            }
            NSArray *rootArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            
            // 数组初始化
            self.categoryArray = [NSMutableArray array];
            // 遍历数组
            for (NSDictionary *dic in rootArray) {
                CategoryModel *model = [[CategoryModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.categoryArray addObject:model];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
        [dataTask resume];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
